<template>
  <el-dialog
    title="重置密码"
    width="400px"
    :close-on-click-modal="false"
    destroy-on-close
    :visible="dialogVisible"
    @close="close"
  >
    <el-form
      ref="ruleForm"
      label-width="auto"
      :model="ruleForm"
      :rules="rules"
      :validate-on-rule-change="false"
    >
      <el-form-item label="新密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPass">
        <el-input v-model="ruleForm.confirmPass" placeholder="请确认密码" type="password" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitData">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import { UserResetPass } from "api/sys/user";
import { encrypt } from "@/libs/rsaEncrypt";
export default {
  mixins: [dialogMixin],
  props: {
    // 当前行数据
    currentRowObj: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      ruleForm: {
        password: "",
        confirmPass: "",
      },
      rules: null,
    };
  },
  methods: {
    /**
     * 初始化
     */
    initForm() {
      this.rules = {
        password: [
          {
            validator: this.validatePass,
            required: true,
            trigger: ["blur", "change"],
          },
        ],
        confirmPass: [
          {
            validator: this.validatePass2,
            required: true,
            trigger: ["blur", "change"],
          },
        ],
      };
    },
    validatePass(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度不能小于6位"));
      } else {
        if (this.ruleForm.confirmPass !== "") {
          this.$refs.ruleForm.validateField("confirmPass");
        }
        callback();
      }
    },
    validatePass2(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度不能小于6位"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },
    /**
     * 提交
     */
    async doSubmit() {
      try {
        await UserResetPass({
          id: this.currentRowObj.id,
          password: encrypt(this.ruleForm.confirmPass),
        });
        this.$message.success("密码重置成功");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
  },
};
</script>
